package utils;

import java.sql.*;

/**
 * 数据库访问工具类
 */
public class JdbcUtils {
    //可以把几个字符串定义成常量：用户名，密码，URL，驱动类
    // 使用final 定义的变量，不允许修改
    private static final String USER = "root";
    private static final String PWD = "root";
    private static final String URL = "jdbc:mysql:///test?characterEncoding=utf8";
    private static final String DRIVER= "com.mysql.jdbc.Driver";
    /**
     * 注册驱动。类加载的时候，静态代码块就执行
     */
    static {
        try {
            Class.forName(DRIVER);
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    /**
     * 得到数据库的连接对象
     */
    public static Connection getConnection() throws SQLException {
        return DriverManager.getConnection(URL,USER,PWD);
    }
    /**
     * 关闭所有打开的资源
     */
    public static void close(Connection conn, Statement stmt) {
        if (stmt!=null) {
            try {
                stmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn!=null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
    /**
     * 关闭所有打开的资源
     */
    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        if (rs!=null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        close(conn, stmt);
    }

    public static void close(Connection con ,PreparedStatement preparedStatement){
        try {
            if(preparedStatement != null && !preparedStatement.isClosed()){
                preparedStatement.close();
            }
            if(con != null && !con.isClosed()){
                con.close();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    public static void main(String[] args) throws SQLException {
        Connection connection = getConnection();
        System.out.println(connection);
    }

}
